import React, { Component } from "react";
import { Table, Input, Button, Popconfirm, Form ,Divider,Select, Upload,  Icon, Modal,Row,Col} from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";
const { Item } = Form;

const props = {
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  listType: 'picture',
  // defaultFileList: [...fileList],
};

const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} 不能为空.`,
              
            },
          ],
          initialValue: record[dataIndex],
        })(<Input className='InputValue' ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"

        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '序号',
        dataIndex: 'id',
        fixed: 'left',
        width:90,
        editable: true,
      },
      {
        title: '发酵样品编号',
        dataIndex: 'f_fjypid',
        fixed: 'left',
        width:120,
        editable: true,
      },

      {
        title: '入库数量',
        dataIndex: 'in_number',
        fixed: 'left',
        width:100,
        editable: true,
      },
      {
        title: '存放位置',
        dataIndex: 'store_place',
        fixed: 'left',
        width:200,
        editable: true,
      },
      {
        title: '备注说明',
        dataIndex: 'remark',
        width:200,
        editable: true,
      },
      {
        title: '入库时间',
        dataIndex: 'f_time',
        width:200,
        editable: true,
      },

      {
        title: '菌株保藏编号',
        dataIndex: 'jzbc_id',
        editable: true,
      },
      {
        title: '发酵人',
        dataIndex: 'f_person',
        editable: true,
      },
      {
        title: '发酵批号',
        dataIndex: 'f_ph',
        editable: true,
      },
      {
        title: '发酵温度（℃）',
        dataIndex: 'f_wd',
        editable: false,
        render: (text, record) => (
          <Select defaultValue={text}
          style={{ width: "100%" }}
          onChange={(value) => this.setState({f_wd: value})}
          tokenSeparators={[","]}
          showArrow={true}
        >
          <Option value="eb">28摄氏度</Option>
          <Option value="yl">16摄氏度</Option>
          <Option value="el">26摄氏度</Option>
          <Option value="qt">其他</Option>
        </Select>
              ),
      },
      {
        title: '发酵培养基编号',
        dataIndex: 'f_pyjid',
        editable: true,
      },
      {
        title: '传代培养基编号',
        dataIndex: 'f_cdid',
        editable: true,
      },
      {
        title: '斜面生长状况',
        dataIndex: 'f_szzk',
        editable: true,
      },
      {
        title: '斜面孢子状况',
        dataIndex: 'f_bzzk',
        editable: true,
      },
      {
        title: '发酵形式',
        dataIndex: 'f_xs',
        render: (text, record) => (
          <Select defaultValue={text}
          style={{ width: "100%" }}
          onChange={(value) => this.setState({f_xs: value})}
          tokenSeparators={[","]}
          showArrow={true}
        >
          <Option value="gt">固体发酵</Option>
          <Option value="yt">液体发酵</Option>
          <Option value="qt">其他发酵</Option>
        </Select>
              )
      },
      {
        title: '发酵周期（h）',
        dataIndex: 'f_zq',
        editable: true,
      },
      {
        title: '其他发酵条件',
        dataIndex: 'f_tj',
        editable: true,
      },
      {
        title: '发酵液颜色',
        dataIndex: 'f_ys',
        editable: true,
      },
      {
        title: '发酵液状况',
        dataIndex: 'f_zk',
        editable: true,
      },      
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width:350,
    
        render: (text, record) => (
            <span>
              <Button type="dashed" onClick={() => this.showDetail(record)} >
                查看
              </Button>
              <Divider type="vertical" />
              <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
                <Button type="dashed" >删除</Button>
              </Popconfirm>
              <Divider type="vertical" />
              <Button  type="dashed" onClick={() => this.handleEdit(record)} disabled={!record.can_ruku}>
                入库
              </Button>
            </span>
          )
      },
    ];

  }

  state = {
    f_xs: [],
    f_wd: [],

    dataSource: [],
    newData: {},
    viewData: {},
    viewModal:false,

    count: 0,
    total: 0,
    loading: true,
    pageNum: 1,
    pageSize: 100
  };

  onShowSizeChange = (current, pageSize) => {
    this.loadData(this.state.acqType, current, pageSize);
    this.setState({
        pageSize: pageSize
    })
  };
  
  paginationProps = {
    showSizeChanger: true,//设置每页显示数据条数
    showQuickJumper: false,
    showTotal: () => `共${this.state.total}条`,
    pageSize: this.state.pageSize,
    total: this.state.total,  //数据的总的条数
    onChange: (current) => this.loadData(current), //点击当前页码
    onShowSizeChange: (current, pageSize) => {//设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        console.log(pageSize);
        this.onShowSizeChange(current, pageSize)
    }
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  // 查看
  showDetail = (record) => {
    this.setState({
      viewData: record,
      viewModal: true
    })
  }
  handleOkDetail = e => {
    this.setState({
      viewModal: false,
    });
  };
  handleCancelDetail = e => {
    this.setState({
      viewModal: false,
    });
  };

  // 入库
  handleEdit = (record) => {
    const dataSource = [...this.state.dataSource];
    const url = global.api.fermentationInfoIn + record.id + '/';
    return global.updatedata.put(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== record.id) });
      Modal.success({
        content: '入库成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '入库出错!',
      });
    })
  }

  handleDelete = id => {
    const dataSource = [...this.state.dataSource];
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }

    const url = global.api.fermentationInfoIn + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const initVal = count + 3241;

    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }

    const newData = {
      id: initVal,
      f_fjypid: initVal,
      sxjj_id : initVal,
      jzbc_id : initVal,
      f_person : initVal,

      in_number : initVal,
      store_place : initVal,
      remark : initVal,

      f_ph: initVal,
      // f_wd : initVal,
      f_pyjid: initVal,
      f_cdid: initVal, 
      f_szzk : initVal,
      // f_xs : initVal,
      f_zq: initVal,
      f_tj: initVal,
      f_ys : initVal,
      f_zk : initVal,

      can_ruku: false,

      f_time: moment(new Date(), 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm')
    };

    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
      newData: newData
    });
  };

  handleSave = (row, showAlert) => {
    let dataSource = [...this.state.dataSource];
    let record = null;
    if( row.id != null ) {
      record = row;
    } else {
      record = dataSource[dataSource.length - 1];
    }

    record.f_xs = this.state.f_xs;
    record.f_wd = this.state.f_wd;

    if( this.state.newData.id != -1 ) {
      const url = global.api.fermentationInfoIn;
      return global.network.post(url, record)
      .then(res => {  
        record.can_ruku = true;
        
        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => record.id === item.id);
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...record,
        });
        
        this.setState({ dataSource: newData, newData: {} });
  
        if( showAlert ) {
          Modal.success({
            content: '保存成功!',
          });
        }
      })
      .catch(err => {
        if( showAlert ) {
          Modal.error({
            content: '保存出错，请检查传入的参数是否已经填写！',
          });
        }
      }) 
    } else {
      const url = global.api.fermentationInfoIn + record.id + '/';
      return global.updatedata.put(url, record)
      .then(res => {  
        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => record.id === item.id);
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...record,
        });
        
        this.setState({ dataSource: newData, newData: {} });
  
        if( showAlert ) {
          Modal.success({
            content: '保存成功!',
          });
        }
      })
      .catch(err => {
        if( showAlert ) {
          Modal.error({
            content: '保存出错，请检查传入的参数是否已经填写！',
          });
        }
      }) 
    }
  };

  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      }
    };    
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
        <Button onClick={this.handleAdd} type="primary" style={{ marginLeft:'24px' }}>
          添加
        </Button>
        <Button disabled={this.state.newData.id == null} onClick={(row) => this.handleSave(row, true)} type="primary" style={{ marginLeft:'50px' }}> 
          保存
        </Button>
        
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          scroll={{ x: 3000}}
        />


        <Modal
          title="Basic Modal"
          visible={this.state.viewModal}
          onOk={this.handleOkDetail}
          onCancel={this.handleCancelDetail}
        >
        <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
        <div style={{display:'flex'}}>
          <span style={{flex:'1'}}>
            <Item label="发酵样品编号"><Input defaultValue={this.state.viewData.f_fjypid } /></Item>
            <Item label="发酵批号"><Input defaultValue={this.state.viewData.f_ph } /></Item>
            <Item label="入库时间"><Input defaultValue={this.state.viewData.f_time } /></Item>
            <Item label="入库数量"><Input defaultValue={this.state.viewData.in_number } /></Item>
            <Item label="存放位置"><Input defaultValue={this.state.viewData.store_place } /></Item>
            <Item label="备注说明"><Input defaultValue={this.state.viewData.remark } /></Item>
            <Item label="工作人员姓名"><Input defaultValue={this.state.viewData.worker } /></Item>
          </span>
        </div>
      </Form>
        </Modal>
       


      </Content>
    );
  }
}

const ActivityScreeningPrimary = Form.create()(EditableTable);
export default ActivityScreeningPrimary;
